package com.boarsoft.boar.gateway.weixin.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class WeixinUser {

	private WeixinPlatformUser wPlatformUser;

	public WeixinUser(WeixinPlatformUser wPlatformUser) {
		this.wPlatformUser = wPlatformUser;
	}

	static Pattern cgiDataP = Pattern.compile("cgiData=\\{(.+)\\};", Pattern.MULTILINE | Pattern.DOTALL);
	static Pattern pageParamP = Pattern.compile("(\\w+)\\s+:\\s+(\\d+),");
	static Pattern p = Pattern.compile("groupsList\\s*:\\s*\\((.+)\\)\\.groups", Pattern.MULTILINE);
	static Pattern userP = Pattern.compile("friendsList\\s*:\\s*\\((.+)\\)\\.contacts", Pattern.MULTILINE);

	/**
	 * 初始化，保证本地库中的用户信息与微信服务器上的用户信息一致
	 */
	public List getAllUser() throws Exception {
		JSONObject paramObject = getUserListResult("0", 0, 10);
		// JSONArray groups = paramObject.getJSONArray("groupList.groups");
		List userList = new ArrayList();
		JSONArray groups = paramObject.getJSONArray("groups");
		for (int i = 0; i < groups.size(); i++) {
			JSONObject group = groups.getJSONObject(i);
			JSONObject groupUser = getUserListResult(group.getString("id"), 0, 10);
			int pageCount = groupUser.getInt("pageCount");
			for (int j = 0; j < pageCount; j++) {
				JSONObject jsonObject = getUserListResult(group.getString("id"), j, 10);
				JSONArray array = jsonObject.getJSONArray("contacts");
				for (int k = 0; k < array.size(); k++) {
					userList.add(array.getJSONObject(k).get("id"));
				}
			}

		}
		return userList;
	}
	public JSONObject getUserListResult(String groupId, int pageIdx, int pageSize) throws Exception{
		String url = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&token="+wPlatformUser.getPlatformUser().getToken()+"&lang=zh_CN&pagesize=10&pageidx="+pageIdx+"&type=0&groupid="+groupId;
		String result = wPlatformUser.getResult(url); 
		Matcher m = cgiDataP.matcher(result);
		JSONObject resultObject = new JSONObject();
		if (m.find()) {
			String cgiData = m.group(1);
			m = pageParamP.matcher(cgiData);
			while (m.find()) {
				resultObject.put(m.group(1), m.group(2));
			}
			m = p.matcher(cgiData);
			JSONObject groupObject = new JSONObject();
			if (m.find()) {
				groupObject = JSONObject.fromObject(m.group(1));
				resultObject.put("groups", groupObject.get("groups"));
			}
			m = userP.matcher(cgiData);
			JSONObject userObject = new JSONObject();
			if (m.find()) {
				userObject = JSONObject.fromObject(m.group(1));
				resultObject.put("contacts", userObject.get("contacts"));
			}
		}
		return resultObject;
	}
	public Object getUserImage(String fakeId) throws Exception{
		String url = "https://mp.weixin.qq.com/cgi-bin/getheadimg?token="+wPlatformUser.getPlatformUser().getToken()+"&fakeid="+fakeId;
		String resultJson = wPlatformUser.getResult(url); 
		JSONObject jsonObject = JSONObject.fromObject(resultJson);
		return jsonObject.getString("result");
	}
	public Map getUserInfo(String fakeId) throws Exception{
		String url = "https://mp.weixin.qq.com/cgi-bin/getcontactinfo?t=ajax-getcontactinfo&lang=zh_CN&fakeid="+fakeId+"&ajax=1&token="+wPlatformUser.getPlatformUser().getToken();
		String jsonResult = wPlatformUser.getResult(url);

		JSONObject jsonObject = JSONObject.fromObject(jsonResult);
		Iterator iterator = jsonObject.keys();
		Map userInfo = new HashMap();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			userInfo.put(key, jsonObject.get(key));
		}
		return userInfo;
	}

	public boolean changeUserMarkName(String fakeId, String markName) throws Exception {
		String url = "https://mp.weixin.qq.com/cgi-bin/modifycontacts?t=ajax-response&action=setremark";
		url = url + "&remark="+markName+"&tofakeuin="+fakeId+"&token="+wPlatformUser.getPlatformUser().getToken()+"&ajax=1";
		String jsonResult = wPlatformUser.getResult(url);
		JSONObject jsonObject = JSONObject.fromObject(jsonResult);
		if ("0".equals(jsonObject.getBoolean("ret"))) {
			return true;
		}
		return false;
	}

	public boolean addUserToGroup(List fakeIds, String groupId) throws Exception {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < fakeIds.size(); i++) {
			sb.append(fakeIds.get(i));
			if (i != fakeIds.size() - 1) {
				sb.append("|");
			}
		}
		String url = "https://mp.weixin.qq.com/cgi-bin/modifycontacts?action=modifycontacts&t=ajax-putinto-group";
		url = url + "&contacttype="+groupId+"&tofakeidlist="+sb.toString()+"&token="+wPlatformUser.getPlatformUser().getToken()+"&ajax=1";
		String jsonResult = wPlatformUser.getResult(url);
		JSONObject jsonObject = JSONObject.fromObject(jsonResult);
		if ("0".equals(jsonObject.getBoolean("ret"))) {
			return true;
		}
		return false;
	}

}
